<script setup>
import { useUserStore } from '@/stores';
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from "vue";
import { userLoginService } from "@/api/user";
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
const router = useRouter()
const userStore = useUserStore()
const form = ref({
  username: '',
  password: ''
})

// 获取表单
const formEl = ref()
// 表单校验
const rules = {
  username: [
    {
      required: true, message: '请填写用户名', trigger: 'blur'
    }
  ],
  password: [
    {
      required: true, message: '请填写用户密码', trigger: 'blur'
    }
  ]
}
// 登录事件
const onSubmit = () => {
  // 提交前再次校验
  if (!formEl.value) return
  formEl.value.validate(async (valid) => {
    if (valid) {
      const { result } = await userLoginService(form.value)
      if (result != null) {
        if (result.status !== "1") return ElMessage.error("该账号以禁用")
        userStore.setToken({ token: result.token })
        userStore.setUser({ username: result.username, password: result.password })
        router.push("/management")
        ElMessage.success("登录成功")
      } else {
        ElMessage.error("用户名或密码错误")
      }
    } else {
      ElMessage.error("请输入用户名或密码")
    }
  })


}
</script>

<template>
  <el-row class="main">
    <el-col :span="12" :offset="6">
      <el-form :model="form" :rules="rules" ref="formEl">
        <el-form-item class="title">
          <h3>苍穹外卖</h3>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" size="large" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="large" :prefix-icon="Lock" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" round size="large" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>

    </el-col>
  </el-row>
</template>
<style>
.el-form-item__content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.main {
  margin-top: 100px;
}
</style>
<style scoped>
.el-button {
  width: 100%;
}
</style>
